package com.webchat.ugc.service.mall.im;


import com.webchat.domain.vo.dto.mall.im.AIGCRecommendAnswerReqDTO;
import com.webchat.domain.vo.dto.mall.im.UgcServerMessageDTO;
import com.webchat.domain.vo.request.mall.im.MallChatRecommendAnswerReqVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.domain.vo.response.mall.MallShopBaseVO;
import com.webchat.rmi.aigc.AIMallServiceClient;
import com.webchat.ugc.service.AccountService;
import com.webchat.ugc.service.mall.MallShopService;
import com.webchat.ugc.service.mall.im.convert.ChatMessageConverter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Service
public class MallAiBotService {


    @Autowired
    private MallShopService shopService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private MallChatMessageService chatMessageService;

    @Autowired
    private AIMallServiceClient aiMallServiceClient;

    @Autowired
    private WebClient aigcWebClient;

    /**
     * ai推荐回复，取最新的50条对话消息作为上下文参考
     */
    private static final int RECOMMEND_MESSAGE_COUNT = 50;

    public Flux<String> recommendAnswers(MallChatRecommendAnswerReqVO chatRecommendAnswerReqVO) {

        // 登录的商家账号
        String loginAccount = chatRecommendAnswerReqVO.getAccount();
        String userAccount = chatRecommendAnswerReqVO.getChatAccount();
        AIGCRecommendAnswerReqDTO req = new AIGCRecommendAnswerReqDTO();
        req.setAccount(loginAccount);
        req.setChatAccount(userAccount);
        req.setRecommendSize(chatRecommendAnswerReqVO.getRecommendSize());
        // 获取当前店铺信息
        Long shopId = shopService.getManageShopId(loginAccount);
        MallShopBaseVO shop = shopService.shopInfo(shopId);
        req.setShopId(shopId);
        req.setShopName(shop.getName());
        // 获取当前对话买家账号信息
        UserBaseResponseInfoVO user = accountService.accountInfo(userAccount);
        if (user != null) {
            req.setChatAccountName(user.getUserName());
        } else {
            req.setChatAccountName("买家");
        }
        // 获取对话消息记录
        List<UgcServerMessageDTO> messages = chatMessageService.list(loginAccount, userAccount, null, RECOMMEND_MESSAGE_COUNT, 1);
        // 买家与商家对话上文消息
        List<AIGCRecommendAnswerReqDTO.MessageDTO> historyMessages = new ArrayList<>();
        // 待回复的买家消息
        List<AIGCRecommendAnswerReqDTO.MessageDTO> waitRelyMessages = new ArrayList<>();
        req.setHistoryMessages(historyMessages);
        req.setWaitRelyMessages(waitRelyMessages);
        if (CollectionUtils.isNotEmpty(messages)) {
            int historyMessageIndex = 0;
            for (int i = messages.size() - 1; i >= 0; i--) {
                if (ObjectUtils.equals(String.valueOf(shopId), messages.get(i).getSenderId())) {
                    historyMessageIndex = i;
                    break;
                }
            }
            for (int i = 0; i < messages.size(); i++) {
                UgcServerMessageDTO messageDTO = messages.get(i);
                boolean isShopMsg = ObjectUtils.equals(String.valueOf(shopId), messageDTO.getSenderId());
                String messageSenderName = isShopMsg ? req.getShopName() : req.getChatAccountName();
                String chatMessage = ChatMessageConverter.text(messageDTO);
                if (i > historyMessageIndex) {
                    waitRelyMessages.add(new AIGCRecommendAnswerReqDTO.MessageDTO(messageSenderName, chatMessage));
                } else {
                    historyMessages.add(new AIGCRecommendAnswerReqDTO.MessageDTO(messageSenderName, chatMessage));
                }
            }
        }
        return aigcWebClient.post()
                .uri("/aigc-service/mall/im/recommend/answer")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(req)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class);
    }
}
